package jgl.vajra.management.dialogFragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.maning.updatelibrary.InstallUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.VersionUpdateBean;
import jgl.vajra.management.databinding.DialogUpdateApkBinding;
import jgl.vajra.management.widget.dialogfragment.BaseDialogFragment;
import jgl.vajra.management.widget.utils.ToastUtils;


/**
 * Created by Administrator on 2018/9/18.
 */

public class UpdateApkDialogFragment extends BaseDialogFragment<DialogUpdateApkBinding> {
    private VersionUpdateBean updateApkBean;
    private FragmentActivity activity;
    private long exitTime;

    private InstallUtils.DownloadCallBack downloadCallBack;
    private String apkDownloadPath;

    @Override
    public void initView(Context context, View rootView, AttributeSet attrs) {
        mBinding.setView(this);
        mBinding.setData(updateApkBean);
        initCallBack();
    }

    @Override
    public void initData(Context context) {
        setCancelable(false);
    }

    @Override
    public void initEvent(Context context) {
        getDialog().setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    ToastUtils.showShort(R.string.Click_again_to_return_desktop);
                    exitTime = System.currentTimeMillis();
                } else {
                    System.exit(0);
                }
                return true;
            }
            return false;
        });
    }


    //点击
    @Override
    public boolean getCancelOutside() {
        return false;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_update_apk;
    }

    public void initDialogConfig(VersionUpdateBean updateApkBean, FragmentActivity activity) {
        this.updateApkBean = updateApkBean;
        this.activity = activity;
    }

    public void leftClick() {
        if (!updateApkBean.enforce) {
            dismiss();
        } else {
            System.exit(0);
        }
    }

    public void update() {
        //先判断有没有安装权限
        InstallUtils.checkInstallPermission(getBaseActivity(), new InstallUtils.InstallPermissionCallBack() {
            @Override
            public void onGranted() {
                //下载
                downloadApk();
            }

            @Override
            public void onDenied() {
                //弹出弹框提醒用户
                AlertDialog alertDialog = new AlertDialog.Builder(getBaseActivity())
                        .setTitle("温馨提示")
                        .setMessage("必须授权才能安装APK，请设置允许安装")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //打开设置页面
                                InstallUtils.openInstallPermissionSetting(getBaseActivity(), new InstallUtils.InstallPermissionCallBack() {
                                    @Override
                                    public void onGranted() {
                                        //下载
                                        downloadApk();
                                    }

                                    @Override
                                    public void onDenied() {
                                        //还是不允许咋搞？
                                        //ToastUtils.showShort("不允许安装咋搞？强制更新就退出应用程序吧！");
                                        if (!updateApkBean.enforce) {
                                            dismiss();
                                        } else {
                                            System.exit(0);
                                        }
                                    }
                                });
                            }
                        })
                        .create();
                alertDialog.show();
            }
        });
    }

    @Override
    public int getGravity() {
        return Gravity.CENTER;
    }

    private void downloadApk() {
        InstallUtils.with(getBaseActivity())
                //必须-下载地址
                .setApkUrl(updateApkBean.name)
                //非必须-下载保存的文件的完整路径+name.apk
                //.setApkPath(Constants.APK_SAVE_PATH)
                //非必须-下载回调
                .setCallBack(downloadCallBack)
                //开始下载
                .startDownload();
    }

    @Override
    public void onResume() {
        super.onResume();
        //设置监听,防止其他页面设置回调后当前页面回调失效
        if (InstallUtils.isDownloading()) {
            InstallUtils.setDownloadCallBack(downloadCallBack);
        }
    }


    private void initCallBack() {
        downloadCallBack = new InstallUtils.DownloadCallBack() {
            @Override
            public void onStart() {
                Logger.d("InstallUtils---onStart");
                mBinding.llUpdateButton.setVisibility(View.GONE);
                mBinding.llUpdateProgress.setVisibility(View.VISIBLE);
             /*   tv_progress.setText("0%");
                tv_info.setText("正在下载...");*/
                mBinding.tvProgress.setText("0% 正在努力下载…");
            }

            @Override
            public void onComplete(String path) {
                Logger.d("InstallUtils---onComplete:" + path);

                //获取文件大小
                File file = new File(path);
                long fileSizes = getFileSizes(file);
                //APK大于1MB
                if (fileSizes <= 1 * 1024 * 1024) {
                    Logger.d("文件异常，请稍后重试:" + fileSizes);
                }
                apkDownloadPath = path;
                /*tv_progress.setText("100%");
                tv_info.setText("下载成功");*/
                mBinding.progress.setProgress(100);
                mBinding.tvProgress.setText("下载完成");
                dismiss();
                //去安装APK,必须外层保证有安装权限
                installAPK(apkDownloadPath);
            }

            @Override
            public void onLoading(long total, long current) {
                //内部做了处理，onLoading 进度转回progress必须是+1，防止频率过快
                Logger.d("InstallUtils----onLoading:-----total:" + total + ",current:" + current);
                int progress = (int) (current * 100 / total);
                //tv_progress.setText(progress + "%");
                mBinding.progress.setProgress(progress);
                mBinding.tvProgress.setText(progress + "% 正在努力下载…");
            }

            @Override
            public void onFail(Exception e) {
                dismiss();
                Logger.d("InstallUtils---onFail:" + e.getMessage());
                mBinding.tvProgress.setText("下载失败");

            }

            @Override
            public void cancle() {
                dismiss();
                mBinding.tvProgress.setText("下载取消");
                Logger.d("InstallUtils---cancle");

            }
        };
    }

    //调用系统的安装方法
    private void installAPK(String path) {
        File savedFile =  new File(path);
        //调用系统的安装方法
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", savedFile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Logger.d("AutoUpdate","7.0data="+data);
        } else {
            data = Uri.fromFile(savedFile);
            Logger.d("AutoUpdate","111data="+data);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }

    private void installApk(String path) {
        InstallUtils.installAPK(getBaseActivity(), path, new InstallUtils.InstallCallBack() {
            @Override
            public void onSuccess() {
                //onSuccess：表示系统的安装界面被打开
                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                ToastUtils.showShort("正在安装程序");
            }

            @Override
            public void onFail(Exception e) {
                Logger.d("安装失败:" + e.toString());
            }
        });
    }

    public long getFileSizes(File f) {
        try {
            long s = 0;
            if (f.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(f);
                s = fis.available();
                fis.close();
            }
            return s;
        } catch (Exception e) {
            return 0;
        }
    }
}
